﻿@using JxAudio.Core.Options
@using System.Diagnostics.CodeAnalysis
@using Jx.Toolbox.Cryptography
@using JxAudio.Core
@using JxAudio.Core.Entity
@using JxAudio.Core.Service
@using JxAudio.Web.Utils
@using JxAudio.Web.Vo
@using Microsoft.Extensions.Localization
@using Newtonsoft.Json.Linq
@using Constants = JxAudio.Core.Constants

@using Newtonsoft.Json
@inject NavigationManager NavigationManager
@inject SwalService SwalService
@inject SettingsService SettingsService
@inject UserService UserService

<GroupBox class="install_content">
    <div class="text-center">
        <h2>@Content</h2>
    </div>
    @if (_isFinish)
    {
        <CountDown CountDownSecond="3" OnTimeout="@OnTimeout"></CountDown>
    }
    
</GroupBox>

@code {

    [Parameter]
    [NotNull]
    public DbConfigOption? DbConfigOption { get; set; }

    [Parameter]
    [NotNull]
    public SettingsVo? SettingsVo { get; set; }

    [Parameter]
    [NotNull]
    public UserInstallVo? UserInstallVo { get; set; }

    [Inject]
    [NotNull]
    public IStringLocalizer<FinishStep>? FinishLocalizer { get; set; }

    private bool _isFinish;

    private string? Content { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        Content = FinishLocalizer["SetupDb"];
        if (!Setup.CreateTables(DbConfigOption))
        {
            await SwalService.Show(new SwalOption()
            {
                Category = SwalCategory.Error,
                Title = FinishLocalizer["Fail"],
                Content = FinishLocalizer["CreateTableFail"],
            });
            Content = FinishLocalizer["CreateTableFail"];
            return;
        }

        Content = FinishLocalizer["SetupSettings"];
        SettingsVo.SetSettings(SettingsService);
        var aesKey = AesEncryption.CreateKey();
        var filePath = Path.Combine(AppContext.BaseDirectory, "config", "settings.json");
        var jObject = File.Exists(filePath) ? JsonConvert.DeserializeObject<JObject>(await File.ReadAllTextAsync(filePath))! : new JObject();
        jObject["JxAudio"] = JObject.FromObject(new { AesKey = aesKey });
        await File.WriteAllTextAsync(filePath, JsonConvert.SerializeObject(jObject, Formatting.Indented));
        Constants.AesKey = aesKey;

        Content = FinishLocalizer["SetupUser"];
        var userEntity = new UserEntity()
        {
            UserName = UserInstallVo.UserName,
            Password = UserInstallVo.Password,
            MaxBitRate = UserInstallVo.MaxBitRate,
            Email = UserInstallVo.Email,
            IsAdmin = true
        };
        UserService.EncryptPassword(userEntity);
        await userEntity.SaveAsync();
        
        Util.StartJob(SettingsVo);
        File.Create(Path.Combine(AppContext.BaseDirectory, "config", "install.lock"));
        Util.IsInstalled = true;

        _isFinish = true;
        Content = FinishLocalizer["Finish"];

    }

    private Task OnTimeout()
    {
        NavigationManager.NavigateTo("/Admin");
        return Task.CompletedTask;
    }
}